package com.wuyan.wurpc.serializer;

import com.wuyan.wurpc.spi.SpiLoader;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 序列化工厂(用于获取序列化器对象)
 */
public class SerializerFactory {

    static {
        SpiLoader.load(Serializer.class);
    }
    /**
     * 默认序列化器
     */
    private static final Serializer DEFAULT_SERIALIZER = new JdkSerializer();

    /**
     * 单例实例
     */
    private static volatile Serializer instance;

    /**
     * 获取实例
     *
     * @param key
     * @return
     */
    public static Serializer getInstance(String key) {
        if (instance == null) {
            synchronized (SerializerFactory.class) {
                if (instance == null) {
                    // 采用SPI加载器获取实例
                    instance = SpiLoader.getInstance(Serializer.class, key);
                    if (instance == null) {
                        instance = DEFAULT_SERIALIZER; // 使用默认序列化器
                    }
                }
            }
        }
        return instance;
    }
}
